﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Web;

namespace gnet1.Models
{
  public class HomePageViewModel
  {
    public string Name { get; set; }
    public string Email { get; set; }
    public string Error { get; set; }
    private static long PageCounter { get; set; }
    private readonly string path = HttpContext.Current.Server.MapPath("~/test/pagecounter.txt");
    private readonly string ConnectionString;

    private Object thisLock = new Object();
    private long outputValue;

    public HomePageViewModel()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
    }

    public long GetCounter()
    {
      string me;
      try
      {
        using (var conn = new SqlConnection(ConnectionString))
        using (var cmd = new SqlCommand("dbo.RecordVisit", conn))
        {
          conn.Open();

          // Stored Proc method
          cmd.CommandType = CommandType.StoredProcedure;
          SqlParameter retval = cmd.Parameters.AddWithValue("@id", SqlDbType.BigInt);
          retval.Direction = ParameterDirection.Output;
          cmd.ExecuteNonQuery();

          var outme = cmd.Parameters["@id"].Value;
         
          return (Convert.ToInt64(outme));      
        }
      }
      catch (Exception ex)
      {
        return 1000;
      }
    }

    /*
    public HomePageViewModel()
    {
      Error = "No Error";

      // Open File and read page counter value
      try
      {
        if (File.Exists(path))
        {
          string value1 = File.ReadAllText(path);
          PageCounter = long.Parse(value1);
         }
        else
        {
          using (StreamWriter sw = File.CreateText(path))
          {
            sw.WriteLine("0");
          }
          PageCounter = 1;
        }
      }
      catch (Exception ex)
      {
        PageCounter = 1;
        Error = ex.Message;
      }
    }

    
    public long GetCounter()
    {
      lock (thisLock)
      {
        PageCounter++;
        UpdatePageCounterToDisk();
        return PageCounter;
      }
    }
    */

    public void IncrementPushCounter()
    {

    }

    private void UpdatePageCounterToDisk()
    {
      try
      {
        File.WriteAllText(path, PageCounter.ToString());
      }
      catch (Exception ex)
      {
        Error = ex.Message;
      }
    }
  }
}
